package com.example.util;

import com.example.annotation.ExcelColumnProperty;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class ExcelColumnUtil {

    public static List<Field> listFields(Class type){
        type = Objects.requireNonNull(type);
        List<Field> result = new ArrayList<>();

        // public, protected, default (package) access, and private fields, but excludes inherited fields.
        // 注意，getDeclaredFields方法不会返回父类中定义的字段
        Field[] declaredFields = type.getDeclaredFields();
        for (Field field : declaredFields){
            if(field.isAnnotationPresent(ExcelColumnProperty.class)){
                result.add(field);
            }
        }
        return result;
    }

    public static int getColumnIndex(Field field){
        ExcelColumnProperty annotation = field.getAnnotation(ExcelColumnProperty.class);
        annotation = Objects.requireNonNull(annotation);
        return annotation.index();
    }

    public static void setValue(Object instance, Field field, Object value){
        if(!field.isAccessible()){

            try {
                field.setAccessible(true);
                try {
                    field.set(instance, value);
                } catch (IllegalAccessException e) {
                    throw  new RuntimeException(e);
                }
            }finally {
                field.setAccessible(false);
            }

        }
    }
}
